package com.vma.jifu.service.impl;

import com.jfinal.plugin.activerecord.Db;
import com.vma.jifu.bizModel.model.Address;
import com.vma.jifu.service.AddressService;
import com.vma.tools.AppException;
import com.vma.tools.StringUtils;

import java.util.List;

/**
 * Created by chenzui on 2017/6/15.
 */
public class AddressServiceImpl implements AddressService {
    public Address qryDefaultAddressByUser(Integer userId) {
        Address address = null;
        address = Address.dao.findFirst("SELECT * FROM address WHERE  user_id = ? AND is_default = 1 AND status = 1",userId);
        if(address == null){
            throw new AppException("-1","暂无地址，请先添加地址");
        }else {
            return address;
        }
    }

    public List<Address> qryAddressListByUser(Integer userId) {
        List<Address> list = Address.dao.find("SELECT * FROM address WHERE  user_id = ? AND status = 1",userId);
        if(list == null && list.size() == 0){
            throw new AppException("-1","无地址");
        }else {
            return list;
        }
    }

    public void addAddress(Integer userId, String province,
                           String city, String area, String detail, Integer isDefault, String phone, String receiver) {
        if(isDefault == 1){
            Db.update("update address set is_default = 0 where user_id = ?",userId);
        }

        new Address().setStatus(1).setUserId(userId).setArea(area)
                .setCity(city).setProvince(province).setDetail(detail).setIsDefault(isDefault)
                .setPhone(phone).setReceiver(receiver).save();
    }

    public void updateAddress(Integer id,Integer userId, String province, String city, String area, String detail, Integer isDefault, String phoen, String receiver) {
        if(isDefault == 1){
            Db.update("update address set is_default = 0 where user_id = ?",userId);
        }
        Address address = Address.dao.findById(id);
        if(isDefault != null){
            address.setIsDefault(isDefault);
        }
        if(!StringUtils.isEmpty(province)){
            address.setProvince(province);
        }
        if(!StringUtils.isEmpty(city)){
            address.setCity(city);
        }
        if(!StringUtils.isEmpty(area)){
            address.setArea(area);
        }
        if(!StringUtils.isEmpty(detail)){
            address.setDetail(detail);
        }
        if(!StringUtils.isEmpty(phoen)){
            address.setPhone(phoen);
        }
        if(!StringUtils.isEmpty(receiver)){
            address.setReceiver(receiver);
        }
        address.update();

    }

    public void delete(Integer id, Integer userId) {
        Address address = Address.dao.findById(id);
        if(address == null){
            throw new AppException("-1","非法地址");
        }else if(address.getUserId() != userId){
            throw new AppException("-1","非法地址");
        }else {
            address.setStatus(0).update();
        }
    }


}
